package com.fms.gui.emailer.auth;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.Arrays;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.fms.model.messaging.auth.IAuthentication;

public class AuthForm extends JPanel implements IAuthentication
{
	/**
	 * 
	 */
	private static final long	serialVersionUID	= -6770129334820056557L;

	private char[] password;
	
	private JPanel userNameAndPasswordPanel;
	private JTextField	userField;
	private JPasswordField	passwordField;
	
	@SuppressWarnings("deprecation")
	public AuthForm()
	{
		//IEmailData data = _repo.load();
		password = null;
		
		userField = new JTextField();
		//userField.setText(data.getUser());
		
		passwordField = new JPasswordField();
		userNameAndPasswordPanel = new JPanel(new GridLayout(0, 1));
		
		userNameAndPasswordPanel.add(group(new JLabel("User name:"), userField));
		userNameAndPasswordPanel.add(group(new JLabel("Password:"), passwordField));
		System.runFinalizersOnExit(true);
		
	}
	@Override
	public boolean request()
	{
		int answer = JOptionPane.showOptionDialog(null, 
												  userNameAndPasswordPanel, 
												  "Login", 
												  JOptionPane.DEFAULT_OPTION, 
												  JOptionPane.PLAIN_MESSAGE , 
												  null,
												  new String[] {"Continue", "Cancel"}, 
												  "Continue" );
		return answer == 0;
	}
	
	@Override
	public char[] getPassword()
	{		
		purge();
		password = passwordField.getPassword();
		return password;
	}

	@Override
	public String getUser()
	{
		return userField.getText();
	}
	@Override
	public void purge()
	{
		if(password != null)
		{
	        Arrays.fill(password, '0');
	        password = null;
		}
		
	}
	
	public JPanel group(JComponent text, JComponent comp)
	{
		JPanel panel = new JPanel(new BorderLayout());
		
		panel.add(text, BorderLayout.NORTH);
		panel.add(comp, BorderLayout.CENTER);
		return panel;
	}
	
	 protected void finalize () 
	 {
		 if(password != null)
		 {
			 System.err.println("Password exists in memory when destroying! Please call purge!");
			 throw new RuntimeException("Password exists in memory when destroying! Please call purge!");
		 }
     }

}